package com.lebang.service.sys;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.domain.AdSwitchConfig;
import com.lebang.entity.RequestHeaders;
import com.lebang.example.AdSwitchConfigExample;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * ad_switch_config
 *
 * @Author hwq
 * @Date 2020-12-30
 */
@Service
public class AdSwitchConfigService extends BaseService<AdSwitchConfig, Integer, AdSwitchConfigExample> {
    @Autowired
    private RedisClient redisClient;
    private static final String KEY = "ad_switch_config";

    public void init() {
        redisClient.del(KEY);
        List<AdSwitchConfig> switchConfigs = this.selectByExample(null);
        switchConfigs.forEach(s -> s.setSdKeyAppStore(s.getSdkKey() + ":" + s.getAppStore()));
        Map<String, List<AdSwitchConfig>> stringListMap = switchConfigs.stream()
                .collect(Collectors.groupingBy(AdSwitchConfig::getSdKeyAppStore));
        stringListMap.forEach((k, v) -> redisClient.hset(KEY, k,
                JSON.toJSONString(v.stream()
                        .sorted(Comparator
                                .comparing(AdSwitchConfig::getStarCount).reversed())
                        .collect(Collectors.toList()))));
    }

    public Optional<String> selectAdIdByRequest(RequestHeaders requestHeaders, int count, String sdkKey) {
        List<AdSwitchConfig>adSwitchConfigs;
        String key = sdkKey + ":" + requestHeaders.getAppStore();
        Boolean hexists = redisClient.hexists(KEY, key);
        if(hexists){
           adSwitchConfigs=JSON.parseArray(redisClient.hget(KEY,key),AdSwitchConfig.class);
        }else {
            key=sdkKey+":all";
            String hget = redisClient.hget(KEY, key);
            if(hget!=null){
                adSwitchConfigs=JSON.parseArray(hget,AdSwitchConfig.class);
                redisClient.hset(KEY,sdkKey + ":" + requestHeaders.getAppStore(),JSON.toJSONString(adSwitchConfigs));
            }else {
                return Optional.empty();
            }
        }
        if(CollectionUtils.isEmpty(adSwitchConfigs)){
            return Optional.empty();
        }
        for (AdSwitchConfig s:adSwitchConfigs){
          if(count>=s.getStarCount()){
              return Optional.of(s.getAdId());
          }
        }
        return Optional.empty();
    }

}
